const db = require("../config/db");
const {date_format} = require('../utils/utils')

exports.create_diary = async (
    title,
    content_html,
    edit_img,
    content_text,
    res
) => {
    try {
        let edit_img_arr = []
        edit_img.forEach(item=>{
            let obj = {
                diary_img:item
            }
            edit_img_arr.push(obj)
        })
        await db.diary.create({
            data: {
                title: title,
                content_html: content_html,
                content_text: content_text,
                img_list:{
                    create:edit_img_arr
                }
            },
        });
        res.send({
            code: 200,
            msg: '保存成功'
        })
    } catch (e) {
        console.log("111", e);
    }
};

// 获取日寄列表
exports.get_diary_list = async (res) => {
    try {
        const diary_list = await db.diary.findMany({
            include:{
                img_list:{
                    select:{
                        id:true,
                        diary_img:true
                    }
                }
            }
        });
        diary_list.forEach(item=>{
            item.create_time = {
                year:date_format('YYYY',item.createdAt),
                month:date_format('MM',item.createdAt),
                day:date_format('DD',item.createdAt)
            }
        })
        res.send({
            code: 200,
            data: diary_list,
            msg: "成功",
        });
    } catch (e) {
        console.log("111", e);
    }
};

exports.get_diary_detail = async ( diary_id,res) => {
    diary_id = parseInt(diary_id)
    try {
        let result = await db.diary.findUnique({
            where:{
                id:diary_id
            },
            include:{
                img_list:{
                    where:{
                        authorId:diary_id
                    }
                }
            }
        });
        res.send({
            code: 200,
            data: result,
            msg: "成功",
        });
    } catch (e) {
        console.log("111", e);
    }
};

// 删除日寄
exports.delete_diary = async (diary_id,res)=>{
    console.log(diary_id)
    try{
        const deleteDiaryImg = db.DiaryImg.deleteMany({
            where: {
                authorId: diary_id,
            },
          })  
          const deletediary = db.diary.deleteMany({
            where: {
                id: diary_id,
            },
          })
          
          const transaction = await db.$transaction([deleteDiaryImg, deletediary])
          res.send({
            code: 200,
            data: null,
            msg: "删除成功",
        });
        }catch(e){
        console.log(e)
    }
}
